// pages/submitFeedback/submitFeedback.js
const {
  API,
  defaultPage,
  equipStatusEnum,
  CLINIC_MANAGER_CODE,
  wsPath
} = require('../../utils/const.js');
const {
  formVaildate,
  checkCount
} = require('../../utils/formCheckUtil.js');
const {
  getRequest,
  postRequest
} = require('../../utils/request.js');
const re = require('../../utils/request.js');
const {
  EuipFormRoles
} = require('../../utils/rulse.js');
const {
  hasRole
} = require('../../utils/userUtil.js');
import webSocketManager from '../../utils/webSocketManager'
var app = getApp();

Page({

  /**
   * Page initial data
   */
  data: {
    situations: [
      '术后疼痛',
      '术后肿胀',
      '术后出血'
    ],
    selectedSituation: '',
    situationText: '',
    doctors:[],
    selectedDoctorName: '',
    selectedDoctor: {}
  },

  /**
   * Lifecycle function--Called when page load
   */
  onLoad(options) {
    const that = this;
    const socketUrl = wsPath + API.backendWs;
    webSocketManager.connect(socketUrl);
    // 发起请求，获取数据
    getRequest(API.getDoctorList).then(res => {
      that.setData({
        doctors: res
      });
    });
  },

  onDoctorChange: function(e) {
    const index = e.detail.value; // 获取选中的索引
    const selectedDoctor = this.data.doctors[index]; // 根据索引获取选中的医生对象

    // 设置选中的医生对象和名字
    this.setData({
      selectedDoctor: selectedDoctor,
      selectedDoctorName: selectedDoctor.doctorName
    });

    console.log('选中的医生对象:', selectedDoctor);
  },

  onSituationChange(e) {
    this.setData({
      selectedSituation: this.data.situations[e.detail.value]
    });
  },

  onInput(e) {
    this.setData({
      situationText: e.detail.value
    });
  },

  onSubmit() {
    if (this.data.selectedSituation) {
      // 这里可以添加实际提交的代码逻辑
      var user = wx.getStorageSync('userInfo');
      var patientId = user.userId;
      var formValue = {
        'patientId': patientId,
        'doctorId': this.data.selectedDoctor.doctorId,
        'situationType': this.data.selectedSituation,
        'situationContent': this.data.situationText,
        'situationTime': new Date().toISOString()
      };

      const newChatMessage = {
        fromRole: 'patient',
        fromId: patientId,
        toRole: 'doctor',
        toId: this.data.selectedDoctor.doctorId,
        content: this.data.selectedSituation + ':' + this.data.situationText
      };

      console.log(newChatMessage);
      webSocketManager.sendMessage({
        messageType: "ChatMessage",
        message: newChatMessage,
      });

      postRequest(API.addFeedback, formValue).then(res => {
        if (res) {
          const url = `/pages/chatPage/chatpage?id=${this.data.selectedDoctor.doctorId}&name=${this.data.selectedDoctor.doctorName}&role=doctor`;
          console.log('url', url);
          wx.showToast({
            title: '您的反馈已收到，请耐心等待',
            icon: 'success',
            duration: 2000,
            complete: function() {
              // 延时跳转，确保提示显示完毕
              setTimeout(() => {
                wx.navigateTo({
                  url: url,
                });
              }, 2000);  // 2秒钟后跳转
            }
          });
        }
      });
    }
  },

  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady() {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow() {

  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide() {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload() {

  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh() {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom() {

  },

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage() {

  }
})